import React, { useEffect, useState } from 'react';
import {
  Card,
  Row,
  Col,
  Table,
  DatePicker,
  Select,
  Button,
  Statistic,
  Space,
  Upload,
  message,
  Modal,
  Form,
  Input,
  Popconfirm,
  Dropdown,
  Menu,
} from 'antd';
import { Line, Pie } from '@ant-design/charts';
import {
  UploadOutlined,
  DownloadOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import {
  getTrafficList,
  getTrafficSummary,
  getSourceDistribution,
  getConversionTrend,
  importExcel,
  exportData,
  updateTrafficData,
  deleteTrafficData,
  batchUpdateTrafficData,
  batchDeleteTrafficData,
} from '@/services/traffic';
import styles from './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

const TrafficPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [dateRange, setDateRange] = useState<[string, string]>(['', '']);
  const [trafficData, setTrafficData] = useState<any[]>([]);
  const [summary, setSummary] = useState<any>({});
  const [sourceData, setSourceData] = useState<any[]>([]);
  const [trendData, setTrendData] = useState<any[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<any>(null);

  // 加载数据
  const loadData = async () => {
    if (!dateRange[0] || !dateRange[1]) return;

    setLoading(true);
    try {
      const [trafficRes, summaryRes, sourceRes, trendRes] = await Promise.all([
        getTrafficList({
          startDate: dateRange[0],
          endDate: dateRange[1],
          ...searchForm.getFieldsValue(),
        }),
        getTrafficSummary({ startDate: dateRange[0], endDate: dateRange[1] }),
        getSourceDistribution({ startDate: dateRange[0], endDate: dateRange[1] }),
        getConversionTrend({ startDate: dateRange[0], endDate: dateRange[1] }),
      ]);

      setTrafficData(trafficRes.data);
      setSummary(summaryRes);
      setSourceData(sourceRes);
      setTrendData(trendRes);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [dateRange]);

  // 处理文件上传
  const handleUpload = async (file: File) => {
    setUploading(true);
    try {
      await importExcel(file);
      message.success('数据导入成功');
      loadData();
    } catch (error: any) {
      message.error(error.message || '数据导入失败');
    } finally {
      setUploading(false);
    }
    return false;
  };

  // 处理数据导出
  const handleExport = async (type: 'xlsx' | 'csv') => {
    if (!dateRange[0] || !dateRange[1]) {
      message.warning('请选择日期范围');
      return;
    }

    try {
      const blob = await exportData({
        startDate: dateRange[0],
        endDate: dateRange[1],
        type,
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `traffic_data_${new Date().toISOString().split('T')[0]}.${type}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 处理编辑
  const handleEdit = (record: any) => {
    setEditingRecord(record);
    editForm.setFieldsValue(record);
    setEditModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (id: string | number) => {
    try {
      await deleteTrafficData(id);
      message.success('删除成功');
      loadData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (!selectedRows.length) {
      message.warning('请选择要删除的数据');
      return;
    }

    try {
      await batchDeleteTrafficData(selectedRows.map(row => row.id));
      message.success('批量删除成功');
      setSelectedRows([]);
      loadData();
    } catch (error) {
      message.error('批量删除失败');
    }
  };

  // 处理保存编辑
  const handleSaveEdit = async () => {
    try {
      const values = await editForm.validateFields();
      if (editingRecord) {
        await updateTrafficData(editingRecord.id, values);
        message.success('更新成功');
        setEditModalVisible(false);
        loadData();
      }
    } catch (error) {
      message.error('更新失败');
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
    },
    {
      title: '媒介',
      dataIndex: 'medium',
      key: 'medium',
    },
    {
      title: '活动',
      dataIndex: 'campaign',
      key: 'campaign',
    },
    {
      title: '访问量',
      dataIndex: 'visitors',
      key: 'visitors',
      sorter: (a: any, b: any) => a.visitors - b.visitors,
    },
    {
      title: '页面浏览量',
      dataIndex: 'page_views',
      key: 'page_views',
      sorter: (a: any, b: any) => a.page_views - b.page_views,
    },
    {
      title: '转化数',
      dataIndex: 'conversions',
      key: 'conversions',
      sorter: (a: any, b: any) => a.conversions - b.conversions,
    },
    {
      title: '跳出率',
      dataIndex: 'bounce_rate',
      key: 'bounce_rate',
      render: (val: number) => `${val.toFixed(2)}%`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 趋势图配置
  const trendConfig = {
    data: trendData,
    xField: 'date',
    yField: 'conversion_rate',
    seriesField: 'source',
    point: {
      size: 4,
    },
    label: {
      style: {
        fill: '#aaa',
      },
    },
  };

  // 来源分布图配置
  const sourceConfig = {
    data: sourceData,
    angleField: 'total_visitors',
    colorField: 'source',
    radius: 0.8,
    label: {
      type: 'outer',
    },
  };

  return (
    <div className={styles.container}>
      {/* 筛选器 */}
      <Card className={styles.filterCard}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={loadData}
        >
          <Form.Item name="dateRange">
            <RangePicker
              onChange={(_, dateStrings) => setDateRange(dateStrings)}
            />
          </Form.Item>
          <Form.Item name="source">
            <Select
              placeholder="选择来源"
              allowClear
              style={{ width: 200 }}
            >
              {/* TODO: 添加选项 */}
            </Select>
          </Form.Item>
          <Form.Item name="medium">
            <Select
              placeholder="选择媒介"
              allowClear
              style={{ width: 200 }}
            >
              {/* TODO: 添加选项 */}
            </Select>
          </Form.Item>
          <Form.Item name="campaign">
            <Input placeholder="搜索活动" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={loadData}
              >
                搜索
              </Button>
              <Upload
                accept=".xlsx,.xls"
                showUploadList={false}
                beforeUpload={handleUpload}
              >
                <Button
                  type="primary"
                  icon={<UploadOutlined />}
                  loading={uploading}
                >
                  导入数据
                </Button>
              </Upload>
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="xlsx" onClick={() => handleExport('xlsx')}>
                      导出Excel
                    </Menu.Item>
                    <Menu.Item key="csv" onClick={() => handleExport('csv')}>
                      导出CSV
                    </Menu.Item>
                  </Menu>
                }
              >
                <Button icon={<DownloadOutlined />}>导出</Button>
              </Dropdown>
              {selectedRows.length > 0 && (
                <Popconfirm
                  title="确定要删除选中的数据吗？"
                  onConfirm={handleBatchDelete}
                >
                  <Button type="primary" danger>
                    批量删除
                  </Button>
                </Popconfirm>
              )}
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 数据概览 */}
      <Row gutter={16} className={styles.statsRow}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总访问量"
              value={summary.total_visitors}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总页面浏览"
              value={summary.total_page_views}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总转化数"
              value={summary.total_conversions}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均转化率"
              value={summary.overall_conversion_rate}
              suffix="%"
              precision={2}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表展示 */}
      <Row gutter={16} className={styles.chartRow}>
        <Col span={16}>
          <Card title="转化率趋势">
            <Line {...trendConfig} loading={loading} />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="流量来源分布">
            <Pie {...sourceConfig} loading={loading} />
          </Card>
        </Col>
      </Row>

      {/* 数据表格 */}
      <Card title="流量数据明细" className={styles.tableCard}>
        <Table
          columns={columns}
          dataSource={trafficData}
          loading={loading}
          rowKey="id"
          rowSelection={{
            selectedRowKeys: selectedRows.map(row => row.id),
            onChange: (_, rows) => setSelectedRows(rows),
          }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
          }}
        />
      </Card>

      {/* 编辑弹窗 */}
      <Modal
        title="编辑数据"
        visible={editModalVisible}
        onOk={handleSaveEdit}
        onCancel={() => setEditModalVisible(false)}
      >
        <Form
          form={editForm}
          layout="vertical"
        >
          <Form.Item
            name="source"
            label="来源"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="medium"
            label="媒介"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="campaign"
            label="活动"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="visitors"
            label="访问量"
            rules={[{ required: true, type: 'number', min: 0 }]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            name="page_views"
            label="页面浏览量"
            rules={[{ required: true, type: 'number', min: 0 }]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            name="conversions"
            label="转化数"
            rules={[{ required: true, type: 'number', min: 0 }]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            name="bounce_rate"
            label="跳出率"
            rules={[{ required: true, type: 'number', min: 0, max: 100 }]}
          >
            <Input type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TrafficPage; 